package com.jic.point.controller.feign;

import com.jic.common.base.vo.RestResult;
import com.jic.point.api.HaierDeliveryPointApi;
import com.jic.point.model.entity.*;
import com.jic.point.rest.request.ChannelConsume;
import com.jic.point.rest.request.PointsCollectionCommonRequest;
import com.jic.point.rest.request.SignData;
import com.jic.point.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @description: TODO
 * @author: lixuehui
 * @date: 2020/11/13 17:04
 */

@Api(tags = {"Feign-积分增加接口"})
@RequestMapping(value = "/api/point")
@RestController
class HaierSmartHomePointFeign implements HaierDeliveryPointApi {

    @Resource
    private HaierSmartHomePointService haierSmartHomePointService;
    @Resource//第三方机构
    private ConfThirdPartService confThirdPartService;
    @Resource//平台
    private ConfPlatformService confPlatformService;
    @Resource//部门
    private ConfBdService confBdService;
    @Resource//供应商
    private ConfSupplierService confSupplierService;
    @Resource//活动规则
    private ConfActivityRuleService confActivityRuleService;
    @Resource//平台
    private ConfBdPlatfromRelaService confBdPlatfromRelaService;
    @Resource//平台积分流水
    private ConfPlatformLogService confPlatformLogService;
    @Resource //部门流水
    private ConfBdPointLogService confBdPointLogService;
    @Resource//活动流水
    private ConfActivityRuleLogService confActivityRuleLogService;

    /**
     * @Auther: YGH
     * @DATE: 2020/11/26
     * @Return:
     * @Param: 积分领取
     */
    @Override
    @PostMapping("getGrantPoint")
    @ApiOperation(value = "积分新增")
    @Transactional(rollbackFor = Exception.class)
    public RestResult<?> getGrantPoint(@RequestBody PointsCollectionCommonRequest pointsCollectionCommonRequest) {
        SignData signData = new SignData();
        BeanUtils.copyProperties(pointsCollectionCommonRequest, signData);
        //第一层校验
        RestResult restResult = checkPointsReceive(signData);
        if (restResult != null) return restResult;
        //第二层校验
        RestResult restResult1 = checkPointsReceive2(signData);
        if (restResult1 != null) return restResult1;
        //进行积分增加操作    部门划至平台 汇率 100
        if ("DEPARTMENT".equals(signData.getBusiType())) {//部门划至平台
            ConfBdPlatfromRela confBdPlatfromRela = new ConfBdPlatfromRela();
            confBdPlatfromRela.setBdCode(pointsCollectionCommonRequest.getBusiCode());//部门编码
            confBdPlatfromRela.setPlatformCode(pointsCollectionCommonRequest.getPointAddCode());//平台编码
            confBdPlatfromRela.setDeleteFlag(0);//未删除
            confBdPlatfromRela.setAuditSts(1);//审核通过
            confBdPlatfromRela.setType(1);//预算关系
            List<ConfBdPlatfromRela> confBdPlatfromRelas = confBdPlatfromRelaService.getqueryRelevance(confBdPlatfromRela);
            if (confBdPlatfromRelas.size() < 1) return RestResult.error("0015", "当前部门和平台没有预算关系！请添加");
            //有预算关系 进行扣除平台金额    参数为积分 要除去100    金额扣除 是 冻结 还是 直接扣除
            ConfBd confbd = new ConfBd();
            BigDecimal b = new BigDecimal(100);
            confbd.setAvailable(pointsCollectionCommonRequest.getAmount().divide(b));//积分 / 100  = 要扣除金额
            confbd.setCode(pointsCollectionCommonRequest.getBusiCode());//设置平台积分
            int i = confBdService.dbPointDeduction(confbd);
            //插入平台
            ConfPlatform confPlatform = new ConfPlatform();
            confPlatform.setAvailable(pointsCollectionCommonRequest.getAmount());//设置积分
            confPlatform.setCode(pointsCollectionCommonRequest.getPointAddCode());//设置编号
            int ii = confPlatformService.platformPointAdd(confPlatform);
            //插入平台流水
            ConfPlatformLog confPlatformLog = new ConfPlatformLog();
            confPlatformLog.setPlatformCode(pointsCollectionCommonRequest.getPointAddCode());//平台编码
            confPlatformLog.setPointType(2);//积分类型
            confPlatformLog.setDeliveryType(2);//发放类型
            confPlatformLog.setType(1);
            confPlatformLog.setAmount(pointsCollectionCommonRequest.getAmount());
            confPlatformLog.setCreateTime(new Date());
            int iii = confPlatformLogService.saveOrUpdate(confPlatformLog);
            //插入部门流水
            ConfBdPointLog confBdPointLog = new ConfBdPointLog();
            confBdPointLog.setPointType(2);
            confBdPointLog.setDiliveryType(2);
            confBdPointLog.setType(2);
            confBdPointLog.setAmount(pointsCollectionCommonRequest.getAmount().divide(b));
            confBdPointLog.setCreateTime(new Date());
            int iiii = confBdPointLogService.saveOrUpdate(confBdPointLog);
            if (i < 1 || ii < 1 || iii < 1 || iiii < 1) TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//有一条不正确 回滚！
        }
        if ("PLATFORM".equals(signData.getBusiType())) {
            //平台划至活动
            //扣除平台积分
            ConfPlatform confPlatform = new ConfPlatform();
            confPlatform.setAvailable(pointsCollectionCommonRequest.getAmount());
            confPlatform.setCode(pointsCollectionCommonRequest.getBusiCode());
            int i = confPlatformService.platformPointDeduction(confPlatform);
            //添加至活动
            ConfActivityRule confActivityRule = new ConfActivityRule();
            confActivityRule.setAvailable(pointsCollectionCommonRequest.getAmount());
            confActivityRule.setCode(pointsCollectionCommonRequest.getPointAddCode());
            int ii = confActivityRuleService.ActivityPointAdd(confActivityRule);
            //增加活动流水
            ConfActivityRuleLog confActivityRuleLog = new ConfActivityRuleLog();
            confActivityRuleLog.setPointType(2);
            confActivityRuleLog.setDeliveryType(2);
            confActivityRuleLog.setPlatformCode(pointsCollectionCommonRequest.getBusiCode());
            confActivityRuleLog.setActivityRuleCode(pointsCollectionCommonRequest.getPointActivityCode());
            confActivityRuleLog.setType(1);
            confActivityRuleLog.setAmount(pointsCollectionCommonRequest.getAmount());
            confActivityRuleLog.setCreateTime(new Date());
            int iii = confActivityRuleLogService.saveOrUpdate(confActivityRuleLog);
            //增加平台流水
            ConfPlatformLog confPlatformLog = new ConfPlatformLog();
            confPlatformLog.setPlatformCode(pointsCollectionCommonRequest.getPointAddCode());//平台编码
            confPlatformLog.setPointType(2);//积分类型
            confPlatformLog.setDeliveryType(2);//发放类型
            confPlatformLog.setType(2);
            confPlatformLog.setAmount(pointsCollectionCommonRequest.getAmount());
            confPlatformLog.setCreateTime(new Date());
            int iiii = confPlatformLogService.saveOrUpdate(confPlatformLog);
            if (i < 1 || ii < 1 || iii < 1 || iiii < 1) TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//有一条不正确 回滚！
        }
        if ("ACTIVITY_RULE".equals(signData.getBusiType())) {//活动规则 划至 用户

        }
        //记录操作积分日志
        return RestResult.success("ok");
    }

    //积分领取  校验主体  第一层校验
    public RestResult checkPointsReceive(SignData signData) {
        //查询参数业务类型和编码是否为空
        if (signData.getBusiType() != null && "".equals(signData.getBusiType()) && signData.getBusiCode() != null) return RestResult.error("0001", "业务类型或业务类型对应编码不能为空");
        if (signData.getAmount().compareTo(BigDecimal.ZERO) != 1) return RestResult.error("0000", "新增积分必须大于0！！！！！");
        //通过业务类型查询数据
        List<SignData> signData1 = haierSmartHomePointService.selAuthorityList(signData);
        if (signData1.size() < 1) return RestResult.error("0002", "当前操作，业务类型以及编码不存在");
        SignData sign = signData1.get(0);
        if (sign.getStatus() != 2) return RestResult.error("0003", "当前操作，渠道未启用！请先启用");
        if (sign.getAppKey() != null && sign.getSecreKey() != null) return RestResult.error("0004", "标识码和秘钥为空或不匹配");
        //判断是否有新增操作权限
        if (sign.getAddType() != 1) return RestResult.error("0005", "当前新增操作，无权限进行新增积分的操作！");
        return null;
    }

    //积分领取或消耗 第二层校验
    public RestResult checkPointsReceive2(SignData signData) {
        //  `sts` int(2) DEFAULT '0' COMMENT '状态（-3、双向冻结；-2、流入冻结，流出正常，-1、停用，0、初始化；1、启用；2、流入正常，流出冻结；）',
        //第三方机构校验
        if ("THRID_PART_PLATFORM".equals(signData.getBusiType())) {
            List<ConfThirdPart> confThirdParts = confThirdPartService.selThirdPartByCode(signData);
            if (confThirdParts.size() < 1) return RestResult.error("0011", "第三方机构编码有误或不存在！");
            ConfThirdPart confThirdPart = confThirdParts.get(0);
            if (confThirdPart.getSts() == -3) return RestResult.error("0012", "当前第三方机构，状态有误");
            if (confThirdPart.getAuditFlag() == 0) return RestResult.error("0013", "当前第三方机构，未启用");
            if (confThirdPart.getAuditSts() != 1) return RestResult.error("0014", "当前第三方机构，未审核通过");
        }
        //平台校验
        if ("PLATFORM".equals(signData.getBusiType())) {
            List<ConfPlatform> confPlatforms = confPlatformService.selectByPrimaryCode(signData);
            if (confPlatforms.size() < 1) return RestResult.error("0011", "平台编码有误或不存在！");
            ConfPlatform confPlatform = confPlatforms.get(0);
            if (confPlatform.getSts() == -3) return RestResult.error("0012", "当前平台，状态有误");
            if (confPlatform.getAuditFlag() == 0) return RestResult.error("0013", "当前平台，未启用");
            if (confPlatform.getAuditSts() != 1) return RestResult.error("0014", "当前平台，未审核通过");
            List<ConfBdPlatfromRela> platfromRela = confPlatformService.getPlatfromRela(confPlatform);
            if (platfromRela.size() < 1) return RestResult.error("0015", "当前平台编码未绑定唯一结算部门！");
            if (confPlatform.getAvailable().compareTo(signData.getAmount()) == -1) return RestResult.error("0016", "当前平台积分不足！");
        }
        //部门校验
        if ("DEPARTMENT".equals(signData.getBusiType())) {
            List<ConfBd> confBds = confBdService.selConfBdByCode(signData);
            if (confBds.size() < 1) return RestResult.error("0011", "部门编码有误或不存在！");
            ConfBd confBd = confBds.get(0);
            if (confBd.getSts() == -3) return RestResult.error("0012", "当前部门，状态有误");
            if (confBd.getAuditSts() != 1) return RestResult.error("0014", "当前部门，未审核通过");
            BigDecimal b = new BigDecimal(100);
            if (confBd.getAvailable().compareTo(signData.getAmount().divide(b)) == -1) return RestResult.error("0016", "当前部门积分不足！");
        }
        //供应商
        if ("SUPPLY".equals(signData.getBusiType())) {
            List<ConfSupplier> confSuppliers = confSupplierService.selConfSupplierByCode(signData);
            if (confSuppliers.size() < 1) return RestResult.error("0011", "供应商编码有误或不存在！");
            ConfSupplier confSupplier = confSuppliers.get(0);
            if (confSupplier.getSts() == -3) return RestResult.error("0012", "当前供应商，状态有误");
            if (confSupplier.getAuditSts() != 1) return RestResult.error("0014", "当前供应商，未审核通过");
            if (confSupplier.getAvailable().compareTo(signData.getAmount()) == -1) return RestResult.error("0016", "当前供应商积分不足！");
        }
        //活动规则
        if ("ACTIVITY_RULE".equals(signData.getBusiType())) {
            List<ConfActivityRule> confActivityRules = confActivityRuleService.selConfActivityRuleByCode(signData);
            if (confActivityRules.size() < 1) return RestResult.error("0011", "活动规则编码有误或活动规则不存在！");
            ConfActivityRule confActivityRule = confActivityRules.get(0);
            if (confActivityRule.getSts() == -3) return RestResult.error("0012", "当前活动规则，状态有误");
            if (confActivityRule.getAuditSts() != 1) return RestResult.error("0014", "当前活动规则，未审核通过");
            if (confActivityRule.getAvailable().compareTo(signData.getAmount()) == -1) return RestResult.error("0016", "当前当前活动积分不足！");
        }
        return null;
    }
}
